//
//  ReadingMeterDetailVC.swift
//  Employee
//
//  Created by tancheng on 2018/6/25.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import UIKit
import Photos
import SwiftDate
import Moya
import RxSwift

class ReadingMeterDetailVC: BaseVC {

    @IBOutlet weak var scrollV: UIScrollView!
    
    @IBOutlet weak var time: UILabel!
    @IBOutlet weak var meterNumber: UILabel!
    @IBOutlet weak var content: UILabel!
  
    @IBOutlet weak var people: UILabel!
    @IBOutlet weak var status: UILabel!
    
    @IBOutlet weak var pastRead: UITextField!
    @IBOutlet weak var currentRead: UITextField!
    
    @IBOutlet weak var readMeterPeople: UILabel!
    @IBOutlet weak var statusTop: NSLayoutConstraint!//完成为34，未完成为10
    @IBOutlet weak var statusImg: UIImageView!
    
    @IBOutlet weak var imageBg: UIView!
    @IBOutlet weak var imageBgHeight: NSLayoutConstraint!
    
    @IBOutlet weak var subBtnBottom: NSLayoutConstraint!
    @IBOutlet weak var subBtn: UIButton!
    
    @IBOutlet weak var xzImg: UIImageView!
    @IBOutlet weak var infoHeight: NSLayoutConstraint!//132 - 26
    
    
    fileprivate var assets:[PHAsset] = []
    
    //
    //var taskStatus: ReadingMeterTaskStatusType = .waitCommit
    var taskId = ""
    var meterId: String?
    
      var listModel: ReadingMeterTaskModel?
      var completionClosure:(()->())?
    var offLineCompletionClosure:(()->())?
    
    fileprivate var networkStatus: Bool = true
    
    fileprivate var detailModel: ReadingMeterTaskDetailModel!

    fileprivate let reachability: Reachability = Reachability(hostName: "https://www.baidu.com")
    
    lazy var tipLab: UILabel = {
        let lab = UILabel()
        lab.font = GlobalConfig.system12Font
        lab.textColor = UIColor.hex("#323C49", alpha: 0.2)
        lab.text = "最多可以添加4个附件"
        return lab
    }()
    
    lazy var imagePickView: StaffSelectImageView = {
        let vi = StaffSelectImageView(frame: CGRect.zero)
        vi.targetVC = self
        vi.selectedImg = {[weak self] selAssets in
            self?.assets.removeAll()
            for item in selAssets {
                self?.assets.append(item)
            }
        }
        vi.deleteImg = {[weak self] index in
           self?.assets.remove(at: index)
        }
        return vi
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
       
        setupUI()
        
        guard listModel != nil && !hasNetwork() else {
            getData()
            return
        }
        
        self.scrollV.isHidden = false
        self.subBtn.isHidden = false
        detailModel = listModel?.detail
        configData()
        
    }

    func setupUI() {
        
        statusImg.image = UIImage.init(named: "协作巡检完成")
        statusImg.isHidden = true
        
        imageBg.addSubview(imagePickView)
        imagePickView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(52)
            make.height.equalTo(AddMeterImageParamCell.imagePickViewHeight)
        }
        
        imageBg.addSubview(tipLab)
        tipLab.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(imagePickView.snp.bottom).offset(20)
        }
        
        //
        let placeHolderColor = UIColor.hex("#323C49", alpha: 0.5)
        currentRead.setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor")
        currentRead.setValue(GlobalConfig.bold20Font, forKeyPath: "_placeholderLabel.font")
        pastRead.setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor")
        pastRead.setValue(GlobalConfig.bold20Font, forKeyPath: "_placeholderLabel.font")
        
        readMeterPeople.isHidden = true
        statusTop.constant = 10
        
        
        scrollV.isHidden = true
        subBtn.isHidden = true
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func submit(_ sender: UIButton) {
        submitTask()
    }
    

}

extension ReadingMeterDetailVC {
    
    func getData() {
        
        SJApp.showHUD(in: view)
        
        var send = ReadingMeterDetailSend()
        send.taskId = taskId
        send.meterId = meterId
        
        MeterRequest.shared.getReadingMeterTaskDetail(send: send, success: { [weak self] (model) in
            
            runOnMainThread {
                SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                SJApp.hideStateBarHUD()
                
                self?.scrollV.isHidden = false
                self?.subBtn.isHidden = false
                
                self?.detailModel = model//获取到详情
                self?.configData()
            }
            
            
            
        }) {[weak self] in
            //失败
            runOnMainThread {
                SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                SJApp.hideStateBarHUD()
            }
            let _ =  runIndelay(1.5, task: {
                self?.navigationController?.popViewController(animated: true)})
            
        }
    }
    
    ///
    func submitTask() {
        
        guard  !currentRead.text!.isEmpty else {
            showHint("请输入本次读数")
            return
        }
        
        guard currentRead.text!.sj.isMeterRead else {
            showHint("本次读数只能输入1位小数")
            return
        }
        
        guard !taskId.isEmpty else {
            return
        }
        
        var send = ReadingMeterDetailSubmitSend()
        send.taskId = taskId
        send.meterRead = currentRead.text ?? ""
        
        subBtn.isEnabled = false
        
        //
       SJApp.showHUD(in: view)
        
         guard assets.count > 0 else {
            
            guard hasNetwork() else {
                //存入本地，有网时自动上传
                if OffLineUploadReadMeterRecordHelper.shared.saveRecord([send.taskId,send.meterRead,[]]) {
                    runOnMainThread {
                        SJApp.hideHUD(in: self.view)
                        SJApp.hideStateBarHUD()
                        self.showHint("已保存本地，恢复网络将自动上传")
                        self.offLineCompletionClosure?()//wancheng
                    }
                    let _ =  runIndelay(1.5, task: {
                        self.navigationController?.popViewController(animated: true)})
                    
                    
                } else {
                    runOnMainThread {
                        SJApp.hideHUD(in: self.view)
                        SJApp.hideStateBarHUD()
                        self.showHint("保存本地失败")
                        self.subBtn.isEnabled = true
                    }
                    
                }
                return
            }
            
            
            MeterRequest.shared.submitReadingMeterTaskDetail(send: send, success: { [weak self] in
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                    self?.showHint("提交成功")
                    self?.completionClosure?()//wancheng
                }
        
              let _ =  runIndelay(1.5, task: {
                    self?.navigationController?.popViewController(animated: true)
                })
            }) { [weak self] in
                //self.showHint("提交失败")
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                }
                self?.subBtn.isEnabled = true
            }
            return
         }
        
        //
        var tempDatas: [Data] = []
        let uploadImages = PhotoHelper.fetchOriginalPhotos(with: assets)
        
        guard hasNetwork() else {
            //存入本地，有网时自动上传
            if OffLineUploadReadMeterRecordHelper.shared.saveRecord([send.taskId,send.meterRead,uploadImages]) {
                print("存到了本地数据库")
                runOnMainThread {
                    SJApp.hideHUD(in: self.view)
                    SJApp.hideStateBarHUD()
                    self.showHint("已保存本地，恢复网络将自动上传")
                    self.offLineCompletionClosure?()//wancheng
                }
                
                let _ =  runIndelay(1.5, task: {
                    self.navigationController?.popViewController(animated: true)})
                
            } else {
                runOnMainThread {
                    SJApp.hideHUD(in: self.view)
                    SJApp.hideStateBarHUD()
                    self.showHint("保存本地失败")
                    self.subBtn.isEnabled = true
                }
            }
            return
        }
        
       //
        for uploadImage in uploadImages {
            tempDatas.append(uploadImage.uploadData)
        }
        
        
        let _ = FileRequest.shared.uploadImages(datas: tempDatas, progressClosure: { (progress) in
        }) { (ids) in
            
            var imageIds = ""
            
            for item in ids {
                imageIds += item.fileId + ","
            }
            imageIds.removeLast()
            send.fileIds = imageIds
            //
            MeterRequest.shared.submitReadingMeterTaskDetail(send: send, success: { [weak self] in
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                    self?.showHint("提交成功")
                    self?.completionClosure?()//wancheng
                }
                let _ = runIndelay(1.5, task: {
                    self?.navigationController?.popViewController(animated: true)
                })
                
            }) { [weak self] in
               //self.showHint("提交失败")
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                }
                self?.subBtn.isEnabled = true
            }
            
            
            
        }
    }
    
    
    func hasNetwork() -> Bool {
        
        if reachability.currentReachabilityStatus().rawValue == 0 {
            return false
        }
        return true
    }
    
    
}

extension ReadingMeterDetailVC {
    
    func configData() {
        
        let readDate = try? detailModel.meterReadDate.date(format: .custom("yyyy-MM"))
        time.text = readDate?.string(custom: "yyyy年MM月")
        
        meterNumber.text = "仪表号 " + detailModel.meterNumber
        
        content.text = detailModel.title
        
        people.text = detailModel.collaborativeTask
        
        pastRead.text = detailModel.lastRead
        
        readMeterPeople.text = detailModel.readingStaffName
        
        //
        if !detailModel.cooperation {
            xzImg.isHidden = true
            people.isHidden = true
            
            infoHeight.constant = 132 - 26
        }
        
       
        
        //
        guard detailModel.status != .waitCommit || !detailModel.isCommit else {//不是待提交，或者不是次账号来提交
            return
        }
        
        readMeterPeople.isHidden = detailModel.status != .submission
        
        statusImg.isHidden = detailModel.status != .submission
        
        statusTop.constant = detailModel.status == .submission ? 34 : 10
        
        subBtnBottom.constant = -45
        
        subBtn.isHidden = true
        
        tipLab.isHidden = true
        
        imageBgHeight.constant = 160
        
        currentRead.isEnabled = false

        switch detailModel.status {
        case ReadingMeterTaskStatusType.submission:
            status.text = "已抄"
            currentRead.text = detailModel.thisRead
            

        case ReadingMeterTaskStatusType.expired:
            
            status.text = "缺抄"
            currentRead.text = "未抄表"
            currentRead.isEnabled = false
            currentRead.font = GlobalConfig.system20Font
            
        default:
            status.text = "待抄"
            if !detailModel.isCommit {
                currentRead.text = "未抄表"
                currentRead.font = GlobalConfig.system20Font
            }
            
        }
        
        
        
        guard detailModel.status == .submission else {
            imageBg.isHidden = true
            return
        }
        
        guard detailModel.files.count != 0 else {
            imageBg.isHidden = true
            return
        }
        
        //附件配置
        imagePickView.isSelect = false
        imagePickView.files = detailModel.files
        
    }
}

